//
//  ZYSRegisterViewController.m
//  shopSN
//
//  Created by imac on 2016/10/24.
//  Copyright © 2016年 yisu. All rights reserved.
//

#import "ZYSRegisterViewController.h"

@interface ZYSRegisterViewController ()<UITextFieldDelegate>

@property (strong,nonatomic) UIView *backV;
/** 验证码按钮 */
@property (nonatomic, strong) UIButton *codeBtn;
/** 手机号 */
@property (nonatomic, strong) UITextField *phoneTF;
/** 验证码 */
@property (nonatomic, strong) UITextField *codeTF;
/** 密码 */
@property (nonatomic, strong) UITextField *passwordTF;

@property (strong,nonatomic) NSMutableArray* tfArr;

/**推荐人id*/
@property (strong,nonatomic) UITextField *recommendTF;

/** 获取的手机验证码 Str */
@property(nonatomic,copy)NSString *code;
/** 倒计时 */
@property(nonatomic,strong)NSTimer *timer;
/** 计时时间 */
@property(nonatomic,assign)NSInteger time;
//验证短信次数
@property (assign,nonatomic) NSInteger totalNumber;


@end

@implementation ZYSRegisterViewController
#pragma mark - 隐藏标签栏
- (void)viewWillAppear:(BOOL)animated {
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    self.tabBarController.tabBar.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = __AccountBGColor;
    self.title = [NSString stringWithFormat:@"注册%@",simpleTitle];
    _totalNumber = 0;
    [self initView];
}

- (void)initView{
    _tfArr = [NSMutableArray array];
    _backV = [[UIView alloc]initWithFrame:CGRectMake(0, 74, __kWidth, 176)];
    [self.view addSubview:_backV];
    _backV.backgroundColor = HEXCOLOR(0xffffff);
//    NSArray *imgArr = @[@"zc_sj",@"dx",@"mima",@"tjr"];
       NSArray *imgArr = @[@"zc_sj",@"dx",@"mima"];
    if (!_isSms) {
        for (int i=0; i<3; i++) {
            UIView *subV = [[UIView alloc]initWithFrame:CGRectMake(0, 44*i, __kWidth, 44)];
            [_backV addSubview:subV];
            //图片
            UIImageView *titleIV = [[UIImageView alloc]initWithFrame:CGRectMake(15, 12, 20, 20)];
            titleIV.contentMode = UIViewContentModeScaleAspectFit;
            [subV addSubview:titleIV];
            if (i>=1) {
                titleIV.image = MImage(imgArr[i+1]);
            }else{
                titleIV.image = MImage(imgArr[i]);
            }


            //文本框
            UITextField  *textfield = [[UITextField alloc]initWithFrame:CGRectZero];
            textfield.font = MFont(14);
            textfield.tag = i+22;
            textfield.textColor = HEXCOLOR(0x333333);
            textfield.delegate = self;
            [subV addSubview:textfield];
            [_tfArr addObject:textfield];
            if (i==0) {
                _codeBtn = [[UIButton alloc]initWithFrame:CGRectMake(__kWidth-115, 8, 100, 28)];
                _codeBtn.layer.borderWidth = 1;
                _codeBtn.layer.borderColor = __DefaultColor.CGColor;
                _codeBtn.layer.cornerRadius =13;
                _codeBtn.titleLabel.font   = MFont(12);
                [_codeBtn setTitle:@"获取验证码" forState:BtnNormal];
                [_codeBtn setTitleColor:__DefaultColor forState:BtnNormal];
                [_codeBtn addTarget:self action:@selector(codeBtnAction) forControlEvents:BtnTouchUpInside];
                [subV addSubview:_codeBtn];
                _codeBtn.hidden = YES;
                textfield.frame = CGRectMake(CGRectXW(titleIV)+10, 7, CGRectX(_codeBtn)-CGRectXW(titleIV)-10, 30);
                _phoneTF = textfield;
                _phoneTF.placeholder = @"请输入11位手机号";
            }else if(i==1){
                textfield.frame = CGRectMake(CGRectXW(titleIV)+10, 7, CGRectX(_codeBtn)-CGRectXW(titleIV)-10, 30);
                _passwordTF = textfield;
                _passwordTF.placeholder = @"请设置密码(6-16个字符)";
//            }else if (i==2){
//                           }else{
//                textfield.frame =CGRectMake(CGRectXW(titleIV)+10, 7, CGRectX(_codeBtn)-CGRectXW(titleIV)-10, 30);
//                _recommendTF = textfield;
//                _recommendTF.placeholder = @"请输入推荐人的ID";
//
            }
            for (int i=1; i<6; i++) {
                UIImageView *lineIV = [[UIImageView alloc]initWithFrame:CGRectMake(48, 44*i, __kWidth-48, 1)];
                lineIV.backgroundColor = HEXCOLOR(0xd8d8d8);
                [_backV addSubview:lineIV];
                
            }
            
            
        }
    }else{
    for (int i=0; i<4; i++) {
        UIView *subV = [[UIView alloc]initWithFrame:CGRectMake(0, 44*i, __kWidth, 44)];
        [_backV addSubview:subV];

        //图片
        UIImageView *titleIV = [[UIImageView alloc]initWithFrame:CGRectMake(15, 12, 20, 20)];
        titleIV.contentMode = UIViewContentModeScaleAspectFit;
        [subV addSubview:titleIV];
        titleIV.image = MImage(imgArr[i]);

        //文本框
        UITextField  *textfield = [[UITextField alloc]initWithFrame:CGRectZero];
        textfield.font = MFont(14);
        textfield.tag = i+22;
        textfield.textColor = HEXCOLOR(0x333333);
        textfield.delegate = self;
        [subV addSubview:textfield];
        [_tfArr addObject:textfield];
        if (i==0) {
            _codeBtn = [[UIButton alloc]initWithFrame:CGRectMake(__kWidth-115, 8, 100, 28)];
            _codeBtn.layer.borderWidth = 1;
            _codeBtn.layer.borderColor = __DefaultColor.CGColor;
            _codeBtn.layer.cornerRadius =13;
            _codeBtn.titleLabel.font   = MFont(12);
            [_codeBtn setTitle:@"获取验证码" forState:BtnNormal];
            [_codeBtn setTitleColor:__DefaultColor forState:BtnNormal];
            [_codeBtn addTarget:self action:@selector(codeBtnAction) forControlEvents:BtnTouchUpInside];
            [subV addSubview:_codeBtn];
            _codeBtn.hidden = NO;
            textfield.frame = CGRectMake(CGRectXW(titleIV)+10, 7, CGRectX(_codeBtn)-CGRectXW(titleIV)-10, 30);
            _phoneTF = textfield;
            _phoneTF.placeholder = @"请输入11位手机号";
        }else if(i==1){
            //输入验证码 文本框
            textfield.frame = CGRectMake(CGRectXW(titleIV)+10, 7, CGRectX(_codeBtn)-CGRectXW(titleIV)-10, 30);
            _codeTF = textfield;
            _codeTF.placeholder = @"请输入短信验证码";
        }else if (i==2){
            textfield.frame = CGRectMake(CGRectXW(titleIV)+10, 7, CGRectX(_codeBtn)-CGRectXW(titleIV)-10, 30);
            _passwordTF = textfield;
            _passwordTF.placeholder = @"请设置密码(6-16个字符)";
//        }else{
//            textfield.frame =CGRectMake(CGRectXW(titleIV)+10, 7, CGRectX(_codeBtn)-CGRectXW(titleIV)-10, 30);
//            _recommendTF = textfield;
//            _recommendTF.placeholder = @"请输入推荐人的ID";

        }
        for (int i=1; i<6; i++) {
            UIImageView *lineIV = [[UIImageView alloc]initWithFrame:CGRectMake(48, 44*i, __kWidth-48, 1)];
            lineIV.backgroundColor = HEXCOLOR(0xd8d8d8);
            [_backV addSubview:lineIV];

        }
     }
    }
    UIButton *logonBtn = [[UIButton alloc]initWithFrame:CGRectMake(15, 285, __kWidth-30, 44)];
    [self.view addSubview:logonBtn];
    [logonBtn setTitle:@"注册" forState:BtnNormal];
    logonBtn.backgroundColor = __DefaultColor;
    logonBtn.layer.cornerRadius = 5;
    [logonBtn setTitleColor:[UIColor whiteColor] forState:BtnNormal];
    logonBtn.titleLabel.font = MFont(15);
    [logonBtn addTarget:self action:@selector(logon) forControlEvents:BtnTouchUpInside];


}


#pragma mark ==获取验证码==
-(void)codeBtnAction{
    _totalNumber ++;
    if (IsNilString(_phoneTF.text)) {
        [SXLoadingView showAlertHUD:@"手机号码不能为空" duration:SXLoadingTime];
        return;
    }
    if (_phoneTF.text.length!=11) {
        [SXLoadingView showAlertHUD:@"手机号码不正确" duration:SXLoadingTime];
        return;
    }
    /**
     * 移动号段正则表达式
     */
    NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
    /**
     * 联通号段正则表达式
     */
    NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
    /**
     * 电信号段正则表达式
     */
    NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
    NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
    BOOL isMatch1 = [pred1 evaluateWithObject:_phoneTF.text];
    NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
    BOOL isMatch2 = [pred2 evaluateWithObject:_phoneTF.text];
    NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
    BOOL isMatch3 = [pred3 evaluateWithObject:_phoneTF.text];
    if (!(isMatch1||isMatch2||isMatch3)) {
        [SXLoadingView showAlertHUD:@"手机号码不正确" duration:SXLoadingTime];
        return;
    }

    [self.view endEditing:YES];
    [ZHttpRequestService POST:@"Login/sendCode" withParameters:@{@"mobile":_phoneTF.text}  success:^(id responseObject, BOOL succe, NSDictionary *jsonDic) {
        if (succe) {
            NSArray *data=jsonDic[@"data"];
            if (data.count) {
                NSDictionary *dic=data[0];
                _code = dic[@"sms_code"];
            }
            [SXLoadingView showAlertHUD:@"获取成功，注意查收" duration:SXLoadingTime];

        }else{
            [SXLoadingView showAlertHUD:@"获取验证码失败" duration:SXLoadingTime];
        }
    } failure:^(NSError *error) {
        [SXLoadingView showAlertHUD:@"获取验证码失败" duration:SXLoadingTime];
    } animated:NO withView:nil];

    if (_timer) {
        [_timer invalidate];
    }
    _codeBtn.userInteractionEnabled=NO;
    if (_totalNumber >=3) {
     _time = 60*5*_totalNumber/3;
    }else{
     _time=60;
    }
    [_codeBtn setTitle:[NSString stringWithFormat:@"%ld秒后重新获取",(long)_time] forState:BtnNormal];
    _timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(reduceTime:) userInfo:nil repeats:YES];
}

-(void)reduceTime:(NSTimer*)sender{
    _time--;
    if (_time<=0) {
        [sender invalidate];
        _codeBtn.userInteractionEnabled=YES;
        [_codeBtn setTitle:@"获取验证码" forState:BtnNormal];
    }else{
        NSString *btnTilte=[NSString stringWithFormat:@"%d秒后重新获取",_time];
        [_codeBtn setTitle:btnTilte forState:BtnNormal];
    }
}

//判断输入内容是否正确
- (void)checkTextFieldContent {
    //1 phone
    if (IsNilString(_phoneTF.text)) {
        [SXLoadingView showAlertHUD:@"手机号码不能为空" duration:SXLoadingTime];
        return;
    }
    if (_isSms) {
        //2 code
        if (!IsEquallString(_codeTF.text, _code)) {
            [SXLoadingView showAlertHUD:@"验证码不正确" duration:SXLoadingTime];
            return;
        }
    }

    //3 password
    if (IsNilString(_passwordTF.text)) {
        [SXLoadingView showAlertHUD:@"密码不可为空" duration:SXLoadingTime];
        return;
    }
    if (_passwordTF.text.length < 6 || _passwordTF.text.length > 16 ) {
        [SXLoadingView showAlertHUD:@"输入密码不正确" duration:SXLoadingTime];
        return;
    }

}
#pragma mark ==注册==
-(void)logon{
    [self checkTextFieldContent];
    NSLog(@"注册");

    NSDictionary *params =@{@"mobile":_phoneTF.text,
                            @"sms_code":_codeTF.text,
                            @"password":_passwordTF.text
//                            @"id":_recommendTF.text
                            };
    [ZHttpRequestService POST:@"Login/register" withParameters:params success:^(id responseObject, BOOL succe, NSDictionary *jsonDic) {
        if (succe) {
            [SXLoadingView showAlertHUD:@"注册成功" duration:SXLoadingTime];
            [self back];
        }else{
            NSString *message = jsonDic[@"message"];
            [SXLoadingView showAlertHUD:message duration:2];

        }
    } failure:^(NSError *error) {
        [SXLoadingView showAlertHUD:@"注册失败" duration:SXLoadingTime];
        //NSLog(@"%@",error);
    } animated:NO withView:nil];



}

#pragma mark - ===== 移除键盘 =====
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    if (_phoneTF || _passwordTF || _codeTF) {
        [self.view endEditing:YES];
    }
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    for (UITextField *tf in _tfArr) {
        if (textField.tag-21==_tfArr.count) {
            [self.view endEditing:YES];
        }else{
            if (tf.tag == textField.tag+1) {
                [tf becomeFirstResponder];
            }
        }
    }
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
